import pymysql
import hashlib


class Database_operter:
    def __init__(self):
        self.connect = pymysql.Connection \
            (host="192.168.200.203", user="xieyuan", password="Magedu@2020", database="test")
        self.cursor = self.connect.cursor()
        self.sha = hashlib.sha512

    def registor_user(self, name, passwd, role):
        encode_passwd = self.sha(passwd.encode()).hexdigest()

        query = "insert into user(name,passwd,role) values(\"{}\", \"{}\", {});".format(name, encode_passwd, role)
        self.cursor.execute(query)
        self.connect.commit()
        return True

    def user_login(self, name, passwd):
        passwd = self.sha(passwd.encode()).hexdigest()
        print(name, passwd)
        query = "select passwd, role from user where name=\"{}\"".format(name)
        self.cursor.execute(query)
        res = self.cursor.fetchone()
        if not res:
            return
        if res[0] != passwd:
            return 0
        else:
            return res[1]

    def input(self, name, chinese, math, english):
        query = "insert into achieve(name, chinese, math, english) values(\"{}\", {}, {}, {});" \
            .format(name, chinese, math, english)
        # print(name, encode_passwd, role)
        self.cursor.execute(query)
        self.connect.commit()

    def search(self, name):
        query = "select chinese, math, english from achieve where name=\"{}\"".format(name)
        self.cursor.execute(query)
        res = self.cursor.fetchone()
        if not res:
            return
        return {"chinese": float(res[0]), "math": float(res[1]), "english": float(res[2])}

    def close(self):
        self.cursor.close()
        self.connect.close()


# d = Database_operter()
# print(d.user_login('xieyuan', '123123'))
# print(d.user_login('xieyuan1', '123'))
# d.registor_user('xieyuan', '123', 1)
# d.input('小明', 50, 60, 70)

class Search_system:
    def __init__(self):
        self.database = Database_operter()
        self.login_error = {}

    def registry(self, name, passwd, role):
        roleid = None
        if role == "教师":
            roleid = 1
        if role == "学生":
            roleid = 2
        if not roleid:
            print("角色有误，请重新输入！")
            return
        if self.database.registor_user(name, passwd, roleid):
            print("~~~~~~~~~~~~注册成功！~~~~~~~~~~~~~")

    def user_login(self, name, passwd):
        if self.login_error.get(name) == 3:
            print('用户锁定，无法登录')
            return

        success = self.database.user_login(name, passwd)
        print(success)
        if success is None:
            print("该用户不存在！")
        elif success == 0:
            self.login_error[name] = self.login_error.get(name, 0) + 1
            print("密码错误！")
        else:
            print("~~~~~~~~~~~~登录成功！~~~~~~~~~~~~~")
            return success

    def writer(self, st_name, chinese, math, english):
        self.database.input(st_name, chinese, math, english)

    def reader(self, name):
        return self.database.search(name)

    def close(self):
        self.database.close()



search_input = Search_system()
# search_input.registry('xieyuan2', '111111', "学生")
# print(search_input.registry('xieyuan3', '11111', "师"))

if __name__ == '__main__':
    while True:
        try:
            regis_or_login = int(input("准备注册还是登录>>>:\n1.注册;\n2.登录;\n3.退出;\n请输入序号："))
        except ValueError:
            continue

        if regis_or_login == 1:
            input_name = input("注册用户名>>>:")
            input_passwd = input("密码>>>:")
            input_role = input("角色（学生或教师）>>>:")
            search_input.registry(input_name, input_passwd, input_role)

        elif regis_or_login == 2:
            while True:
                input_name = input("登录用户名>>>:")
                input_passwd = input("密码>>>:")
                role = search_input.user_login(input_name, input_passwd)

                if role == 1:
                    while True:
                        try:
                            index = int(input("输入还是查询的成绩>>>:\n1.输入;\n2.查询;\n3.退出;\n请输入序号："))
                        except ValueError:
                            index = 999
                        if int(index) == 1:
                            student_name = input("输入学生姓名：")
                            chinese = input("语文成绩：")
                            math = input("数学成绩：")
                            english = input("英语成绩：")
                            search_input.writer(student_name, chinese, math, english)
                        elif int(index) == 2:
                            student_name = input("输入查询成绩的学生姓名：")
                            res = search_input.reader(student_name)
                            if res:
                                print("语文:{}, 数学:{}, 英语:{}".format(res["chinese"], res["math"], res["english"]))
                            else:
                                print("你输入的学生还没有成绩！")
                        elif int(index) == 3:
                            break
                        else:
                            print("输入有误，请重新输入！")

                elif role == 2:
                    while True:
                        try:
                            index = int(input("输入还是查询的成绩>>>:\n1.查询;\n2.退出;\n请输入序号："))
                        except ValueError:
                            index = 999
                        if int(index) == 1:
                            student_name = input("输入查询成绩的学生姓名：")
                            res = search_input.reader(student_name)
                            if res:
                                print("语文:{}, 数学:{}, 英语:{}".format(res["chinese"], res["math"], res["english"]))
                            else:
                                print("你输入的学生还没有成绩！")
                        elif int(index) == 2:
                            break
                        else:
                            print("输入有误，请重新输入！")

        elif regis_or_login == 3:
            search_input.close()
            break
